package com.example.ivideo_2211a.collection

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.common.mvi.BaseViewActivity
import com.example.common.room.VideoDatabase
import com.example.common.room.VideoRepository
import kotlinx.coroutines.launch
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ActivityCollectionBinding
import androidx.appcompat.app.AlertDialog
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.ivideo_2211a.adapter.CollectionAdapter
import com.google.gson.Gson
import com.example.ivideo_2211a.home.HomeData

@Route(path = "/collection/CollectionActivity")
class CollectionActivity : BaseViewActivity<ActivityCollectionBinding>() {

    private lateinit var collectionAdapter: CollectionAdapter
    private lateinit var videoRepository: VideoRepository
    private var isSelectionMode = false
    private val selectedItems = mutableSetOf<Int>()

    override fun getLayoutId(): Int = R.layout.activity_collection
    
    override fun setupViews() {
        initRepository()
        initToolbar()
        initRecyclerView()
        initClickListeners()
        loadCollectionData()
    }
    
    private fun initRepository() {
        val database = VideoDatabase.getDatabase(this)
        videoRepository = VideoRepository(database.videoFavoriteDao())
    }
    
    private fun initToolbar() {
        // 返回按钮
        binding.backBtn.setOnClickListener {
            finish()
        }
        
        // 选择模式工具栏按钮
        binding.selectAllBtn.setOnClickListener {
            toggleSelectAll()
        }
        
        binding.deleteBtn.setOnClickListener {
            deleteSelectedItems()
        }
        
        binding.closeSelectionBtn.setOnClickListener { // 修改为正确的ID
            exitSelectionMode()
        }
    }
    
    private fun initRecyclerView() {
        collectionAdapter = CollectionAdapter(
            onItemClick = { video ->
                if (isSelectionMode) {
                    toggleItemSelection(video.id)
                } else {
                    // 跳转到播放页面
                    val homeData = HomeData(
                        id = video.id,
                        title = video.title,
                        videopath = video.videopath,
                        avatar_url = video.avatar_url,
                        name = video.name,
                        videomainimag = "", // VideoFavorite中没有这个字段，使用空字符串
                        playnum = 0, // VideoFavorite中没有这个字段，使用0
                        channelid = "",
                        commentnum = 0,
                        ctime = "",
                        description = "",
                        group_id = "",
                        image_url = "",
                        item_id = "",
                        labelIds = "",
                        preview_url = "",
                        publish_time = "",
                        userid = "",
                        verifycode = ""
                    )
                    val videoDataJson = Gson().toJson(homeData)
                    ARouter.getInstance()
                        .build("/playvideo/PlayVideoActivity")
                        .withString("videoDataJson", videoDataJson)
                        .navigation()
                }
            },
            onItemLongClick = { video ->
                if (!isSelectionMode) {
                    enterSelectionMode()
                    toggleItemSelection(video.id)
                }
            }
        )
        
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@CollectionActivity)
            adapter = collectionAdapter
        }
    }
    
    private fun initClickListeners() {
        // 删除按钮已在initToolbar中处理
    }
    
    private fun loadCollectionData() {
        lifecycleScope.launch {
            videoRepository.getAllFavoriteVideos().collect { videos ->
                collectionAdapter.submitList(videos)
                updateEmptyState(videos.isEmpty())
            }
        }
    }
    
    private fun enterSelectionMode() {
        isSelectionMode = true
        binding.selectionToolbar.visibility = View.VISIBLE
        binding.toolbar.visibility = View.GONE // 修改为正确的ID
        collectionAdapter.setSelectionMode(true)
        updateSelectionCount()
    }
    
    private fun exitSelectionMode() {
        isSelectionMode = false
        selectedItems.clear()
        binding.selectionToolbar.visibility = View.GONE
        binding.toolbar.visibility = View.VISIBLE // 修改为正确的ID
        collectionAdapter.setSelectionMode(false)
        collectionAdapter.clearSelection()
        updateSelectionCount()
    }
    
    private fun toggleItemSelection(videoId: Int) {
        if (selectedItems.contains(videoId)) {
            selectedItems.remove(videoId)
        } else {
            selectedItems.add(videoId)
        }
        collectionAdapter.updateSelection(selectedItems)
        updateSelectionCount()
        
        if (selectedItems.isEmpty()) {
            exitSelectionMode()
        }
    }
    
    private fun toggleSelectAll() {
        val allItems = collectionAdapter.currentList.map { it.id }.toSet()
        if (selectedItems.containsAll(allItems)) {
            // 如果已全选，则取消全选
            selectedItems.clear()
            collectionAdapter.clearSelection()
        } else {
            // 否则全选
            selectedItems.clear()
            selectedItems.addAll(allItems)
            collectionAdapter.selectAll()
        }
        updateSelectionCount()
        
        if (selectedItems.isEmpty()) {
            exitSelectionMode()
        }
    }
    
    private fun updateSelectionCount() {
        binding.selectionCountText.text = "已选择 ${selectedItems.size} 项" // 修改为正确的ID
    }
    
    private fun deleteSelectedItems() {
        if (selectedItems.isEmpty()) return
        
        AlertDialog.Builder(this)
            .setTitle("删除选中项")
            .setMessage("确定要删除选中的 ${selectedItems.size} 个视频吗？")
            .setPositiveButton("确定") { _, _ ->
                lifecycleScope.launch {
                    selectedItems.forEach { videoId ->
                        videoRepository.deleteVideo(videoId)
                    }
                    exitSelectionMode()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun deleteAllItems() {
        val totalCount = collectionAdapter.currentList.size
        if (totalCount == 0) return
        
        AlertDialog.Builder(this)
            .setTitle("删除全部")
            .setMessage("确定要删除所有收藏的视频吗？共 $totalCount 个视频。")
            .setPositiveButton("确定") { _, _ ->
                lifecycleScope.launch {
                    collectionAdapter.currentList.forEach { video ->
                        videoRepository.deleteVideo(video.id)
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        binding.emptyStateView.visibility = if (isEmpty) View.VISIBLE else View.GONE // 修改为正确的ID
        binding.recyclerView.visibility = if (isEmpty) View.GONE else View.VISIBLE
    }
    
    override fun onBackPressed() {
        if (isSelectionMode) {
            exitSelectionMode()
        } else {
            super.onBackPressed()
        }
    }
}